#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""
An application that parses a __utm.gif request and presents it in an easy to read
format
""" 

# Import packages
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

#Request handlers
#Define your own request handlers that extend webapp.RequestHandler
class MainHandler(webapp.RequestHandler):
  def __init__(self):
      self.user = users.get_current_user()
      self.templateParams = {}
      self.initTemplateParams()
      
      
  def initTemplateParams(self):
      userNickname = ''
      
      if self.user:
          userNickname = self.user.nickname()
          logLabel = 'Log out'
          logURL = users.create_logout_url('/')
      else:
          logLabel = 'Log in'
          logURL = users.create_login_url('/')
          
      logLink = '<a href="%s">%s</a>' % (logURL, logLabel)
      
      self.templateParams['nick'] = userNickname
      self.templateParams['loglink'] = logLink
      
    
  #Handle GET requests
  def get(self):
    self.response.out.write(template.render('templates/default.html', self.templateParams))
    
  #Handle POST requests
  def post(self):
    import urllib
    import urlparse
    
    gifuri = self.request.get("gifuri") #access the POST parameter
    uri_parts = urlparse.urlparse(gifuri)
    
    query_string = uri_parts.query
    query_parts = query_string.split('&')
    
    output = {}
    for query_part in query_parts:
        key, val = query_part.split('=')
        val = urllib.unquote(val)
        
        if key == 'utmcc':
            cc_parts = val.split(';')
            val = ('<br/>').join(cc_parts)
        
        output[key] = val
        
    self.templateParams['gifuri'] = gifuri
    self.templateParams['output'] = output
    
    print template.render('templates/default.html', self.templateParams)


def main():
  application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
